package logic

import (
	"context"

	"googee/service/inbox/model"
	"googee/service/inbox/rpc/internal/svc"
	"googee/service/inbox/rpc/types/inbox"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type SendMessageLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendMessageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendMessageLogic {
	return &SendMessageLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 发送一条消息
func (l *SendMessageLogic) SendMessage(in *inbox.SendMessageRequest) (*inbox.InboxMessage, error) {
	resp := &inbox.InboxMessage{}

	m := &model.InboxMessage{
		Sender:   in.Sender,
		Receiver: in.Receiver,
		Content:  in.Content,
		Extra:    in.Extra,
	}

	result, err := l.svcCtx.InboxMessageModel.Insert(l.ctx, m)
	if err != nil {
		logx.Error(err)
		return nil, status.Error(codes.Internal, "system error")
	}

	id, err := result.LastInsertId()
	if err != nil {
		logx.Error(err)
		return nil, status.Error(codes.Internal, "system error")
	}

	newone, err := l.svcCtx.InboxMessageModel.FindOne(l.ctx, id)
	if err != nil {
		logx.Error(err)
		return nil, status.Error(codes.Internal, "system error")
	}

	copier.Copy(newone, newone)

	return resp, nil
}
